const menuItems = document.querySelectorAll('.menu-item');
const submenuItems = document.querySelectorAll('.submenu-item');
const currentMenuTitle = document.querySelector('#current-menu .title');

// 全局数据和状态
let exhibitionData = []; // 网上展厅数据
let inquiryData = []; // 朝阳兰台数据
let cultureData = []; // 志鉴文化数据
let currentData = []; // 当前显示的数据
let currentPage = 1; // 当前页码
let pageSize = 10; // 每页显示数量
let totalPages = 1; // 总页数
let currentDataType = 'exhibition'; // 当前显示的数据类型

// 轮播图功能
let currentSlide = 0;
const slides = document.querySelectorAll('.carousel-slide');
const indicators = document.querySelectorAll('.indicator');

function showSlide(index) {
    // 隐藏所有幻灯片
    slides.forEach(slide => slide.classList.remove('active'));
    // 显示指定幻灯片
    slides[index].classList.add('active');

    // 更新指示器
    indicators.forEach(indicator => indicator.classList.remove('active'));
    indicators[index].classList.add('active');

    currentSlide = index;
}

function nextSlide() {
    currentSlide = (currentSlide + 1) % slides.length;
    showSlide(currentSlide);
}

// 自动播放
let slideInterval = setInterval(nextSlide, 3000);

// 指示器点击事件
indicators.forEach((indicator, index) => {
    indicator.addEventListener('click', () => {
        clearInterval(slideInterval);
        showSlide(index);
        slideInterval = setInterval(nextSlide, 3000);
    });
});

// 初始化显示第一张幻灯片
showSlide(currentSlide);

// submenu 显示控制
let activeSubmenu = null;

// 树形菜单功能
const treeItems = document.querySelectorAll('.tree-item');
const treeTexts = document.querySelectorAll('.tree-text');

// 生成朝阳兰台数据
function generateInquiryData() {
    const titles = [
        '朝阳区档案馆开展{year}年度档案业务培训',
        '朝阳区档案信息化建设项目顺利通过验收',
        '朝阳区档案馆举办"铭记历史 砥砺前行"主题展览',
        '朝阳区完成{year}年度文件材料归档工作检查',
        '朝阳区地方志编纂工作取得新进展',
        '朝阳区召开档案工作联席会议 统筹推进全区档案事业发展',
        '朝阳区档案馆新馆建设项目获区政府重点支持',
        '朝阳区"十四五"档案事业发展规划实施情况评估会召开',
        '朝阳区领导调研区档案馆工作 强调做好存史资政育人',
        '朝阳区召开区委常委会会议 研究部署档案工作'
    ];

    const data = [];
    const currentYear = new Date().getFullYear();

    for (let i = 0; i < 300; i++) {
        const titleTemplate = titles[i % titles.length];
        const year = currentYear - Math.floor(i / 100);
        const title = titleTemplate.replace('{year}', year);

        // 生成日期：从当前日期往前推，保证日期唯一
        const date = new Date();
        date.setDate(date.getDate() - i - Math.floor(Math.random() * 30));
        const yearStr = date.getFullYear();
        const monthStr = String(date.getMonth() + 1).padStart(2, '0');
        const dayStr = String(date.getDate()).padStart(2, '0');
        const dateStr = `${yearStr}-${monthStr}-${dayStr}`;

        data.push({
            id: i + 1,
            title: title,
            date: dateStr
        });
    }

    return data.sort((a, b) => new Date(b.date) - new Date(a.date));
}

// 生成志鉴文化数据
function generateCultureData() {
    const titles = [
        '朝阳区{year}年地方志编纂工作圆满完成',
        '《朝阳区志》（{year}版）荣获市级优秀志书奖',
        '朝阳区档案馆举办"志鉴文化"专题展览',
        '朝阳区完成{year}年度年鉴编纂工作',
        '《朝阳区年鉴》（{year}卷）正式出版发行',
        '朝阳区召开志鉴文化资源开发利用研讨会',
        '朝阳区地方志办公室开展志鉴文化进社区活动',
        '朝阳区志鉴数据库建设项目启动',
        '朝阳区举办{year}年志鉴文化节',
        '朝阳区志鉴文化遗产保护工作取得新进展'
    ];

    const data = [];
    const currentYear = new Date().getFullYear();

    for (let i = 0; i < 300; i++) {
        const titleTemplate = titles[i % titles.length];
        const year = currentYear - Math.floor(i / 100);
        const title = titleTemplate.replace('{year}', year);

        // 生成日期：从当前日期往前推，保证日期唯一
        const date = new Date();
        date.setDate(date.getDate() - i - Math.floor(Math.random() * 30));
        const yearStr = date.getFullYear();
        const monthStr = String(date.getMonth() + 1).padStart(2, '0');
        const dayStr = String(date.getDate()).padStart(2, '0');
        const dateStr = `${yearStr}-${monthStr}-${dayStr}`;

        data.push({
            id: i + 1,
            title: title,
            date: dateStr
        });
    }

    return data.sort((a, b) => new Date(b.date) - new Date(a.date));
}

// 渲染数据列表
function renderList(data) {
    const dynamicList = document.querySelector('.dynamic-list');
    if (!dynamicList) return;
    
    dynamicList.innerHTML = '';

    data.forEach(item => {
        const li = document.createElement('li');
        li.className = 'dynamic-item';
        li.innerHTML = `
            <div class="title">${item.title}</div>
            <div class="date">${item.date}</div>
        `;

        // 添加点击事件
        li.addEventListener('click', function () {
            alert('您点击了：' + item.title);
        });

        dynamicList.appendChild(li);
    });
}

// 渲染分页信息
function renderPagination() {
    const pageInfo = document.querySelector('#page-info');
    if (!pageInfo) return;
    
    let pageNumbers = '';

    // 始终显示第一页
    if (currentPage === 1) {
        pageNumbers += '<span class="current page-item">1</span>';
    } else {
        pageNumbers += '<span class="page-item" onclick="goToPage(1)">1</span>';
    }

    // 如果当前页大于4，显示省略号
    if (currentPage > 4) {
        pageNumbers += '<span class="slide">...</span>';
    }

    // 显示当前页前后各两页
    let start = Math.max(2, currentPage - 2);
    let end = Math.min(totalPages - 1, currentPage + 2);

    for (let i = start; i <= end; i++) {
        if (i === currentPage) {
            pageNumbers += `<span class="current page-item">${i}</span>`;
        } else {
            pageNumbers += `<span class="page-item" onclick="goToPage(${i})">${i}</span>`;
        }
    }

    // 如果当前页小于总页数-3，显示省略号
    if (currentPage < totalPages - 3) {
        pageNumbers += '<span class="slide">...</span>';
    }

    // 始终显示最后一页
    if (totalPages > 1) {
        if (currentPage === totalPages) {
            pageNumbers += `<span class="current page-item">${totalPages}</span>`;
        } else {
            pageNumbers += `<span class="page-item" onclick="goToPage(${totalPages})">${totalPages}</span>`;
        }
    }

    pageInfo.innerHTML = pageNumbers;

    // 更新上一页、下一页按钮状态和样式
    const prevBtn = document.querySelector('#prev-page');
    const nextBtn = document.querySelector('#next-page');
    if (prevBtn) prevBtn.disabled = currentPage <= 1;
    if (nextBtn) nextBtn.disabled = currentPage >= totalPages;

    // 为禁用状态的按钮添加样式
    if (prevBtn && prevBtn.disabled) {
        prevBtn.style.backgroundColor = '#f9f9f9';
        prevBtn.style.cursor = 'not-allowed';
    } else if (prevBtn) {
        prevBtn.style.backgroundColor = '';
        prevBtn.style.cursor = '';
    }

    if (nextBtn && nextBtn.disabled) {
        nextBtn.style.backgroundColor = '#f9f9f9';
        nextBtn.style.cursor = 'not-allowed';
    } else if (nextBtn) {
        nextBtn.style.backgroundColor = '';
        nextBtn.style.cursor = '';
    }

    // 更新页码输入框
    const pageInput = document.querySelector('#page-input');
    if (pageInput) pageInput.value = currentPage;
}

// 在全局作用域中定义goToPage函数，使其在HTML中可访问
window.goToPage = function (page) {
    if (page >= 1 && page <= totalPages) {
        currentPage = page;

        // 计算当前页显示的数据
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, currentData.length);
        const pageData = currentData.slice(startIndex, endIndex);

        // 重新渲染列表和分页
        renderList(pageData);
        renderPagination();
    }
};

// 切换页码
function changePage(page) {
    if (page < 1 || page > totalPages) {
        return;
    }

    currentPage = page;

    // 计算当前页显示的数据
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, currentData.length);
    const pageData = currentData.slice(startIndex, endIndex);

    // 重新渲染列表和分页
    renderList(pageData);
    renderPagination();
}

// 切换每页显示数量
function changePageSize(size) {
    pageSize = parseInt(size);
    currentPage = 1;

    // 重新计算总页数
    totalPages = Math.ceil(currentData.length / pageSize);

    // 重新渲染列表和分页
    changePage(1);
}

// 初始化
function init() {
    // 菜单点击事件
    menuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            // 移除所有菜单项的激活状态
            menuItems.forEach(i => i.classList.remove('active'));

            // 添加当前点击项的激活状态
            this.classList.add('active');

            // 显示 submenu（如果存在）
            const submenu = this.querySelector('.submenu');
            if (submenu) {
                // 隐藏之前激活的 submenu
                if (activeSubmenu && activeSubmenu !== submenu) {
                    activeSubmenu.style.display = 'none';
                }

                // 显示当前 submenu
                submenu.style.display = 'flex';
                activeSubmenu = submenu;
            } else {
                // 如果点击的菜单项没有 submenu，隐藏所有 submenu
                document.querySelectorAll('.submenu').forEach(sub => {
                    sub.style.display = 'none';
                });
                activeSubmenu = null;
            }
        });

        // 鼠标移入事件
        item.addEventListener('mouseenter', function () {
            // 隐藏所有已激活的 submenu
            if (activeSubmenu) {
                activeSubmenu.style.display = 'none';
                activeSubmenu = null;
            }

            // 显示当前菜单项的 submenu（如果存在）
            const submenu = this.querySelector('.submenu');
            if (submenu) {
                submenu.style.display = 'flex';
                activeSubmenu = submenu;
            }
        });

        // 鼠标移出事件
        item.addEventListener('mouseleave', function (e) {
            // 检查鼠标是否移向 submenu
            const submenu = this.querySelector('.submenu');
            if (submenu && activeSubmenu === submenu) {
                // 使用 setTimeout 来处理鼠标移出到 submenu 的情况
                setTimeout(() => {
                    if (!submenu.matches(':hover')) {
                        submenu.style.display = 'none';
                        if (activeSubmenu === submenu) {
                            activeSubmenu = null;
                        }
                    }
                }, 100);
            }
        });
    });

    // 二级菜单点击事件
    submenuItems.forEach(item => {
        item.addEventListener('click', function (e) {
            e.stopPropagation(); // 阻止事件冒泡

            // 移除所有菜单项的激活状态
            menuItems.forEach(i => i.classList.remove('active'));

            // 添加父级菜单项的激活状态
            this.closest('.menu-item').classList.add('active');

            // 更新当前菜单显示
            const submenuText = this.textContent;
            if (submenuText) {
                currentMenuTitle.textContent = submenuText;
            }

            // 根据submenu-item关联tree-item和右侧内容
            const submenuType = this.dataset.submenu;
            let targetTreeType = '';

            // 页面跳转逻辑
            let targetUrl = '';
            if (submenuType === 'status1') {
                targetUrl = '../work-status/index.html?type=exhibition';
            } else if (submenuType === 'statu2') {
                targetUrl = '../work-status/index.html?type=inquiry';
            } else if (submenuType === 'service4') {
                targetUrl = '../public-service/index.html?type=exhibition';
            } else if (submenuType === 'service5') {
                targetUrl = '../public-service/index.html?type=inquiry';
            } else if (submenuType === 'service1') {
                targetUrl = '../public-service/index.html?type=reservation';
            } else if (submenuType === 'service2') {
                targetUrl = '../public-service/index.html?type=message';
            } else if (submenuType === 'service3') {
                targetUrl = '../public-service/index.html?type=donation';
            } else if (submenuType === 'overview1') {
                targetUrl = '../archival-collections/index.html?type=inquiry';
            } else if (submenuType === 'overview2') {
                targetUrl = '../archival-collections/index.html?type=exhibition';
            } else if (submenuType === 'culture1') {
                targetUrl = '../chronicle-culture/index.html?type=exhibition';
            } else if (submenuType === 'culture2') {
                targetUrl = '../chronicle-culture/index.html?type=inquiry';
            }

            // 如果有目标URL，则跳转到对应页面
            if (targetUrl) {
                window.location.href = targetUrl;
                return;
            }

            // 建立submenu-item与tree-item的映射关系
            if (submenuType === 'culture1') {
                targetTreeType = 'exhibition';
            } else if (submenuType === 'culture2') {
                targetTreeType = 'inquiry';
            }

            // 如果找到了对应的tree-item，更新其选中状态
            if (targetTreeType) {
                const targetTreeItem = document.querySelector(`.tree-item[data-tree="${targetTreeType}"]`);
                if (targetTreeItem) {
                    // 移除所有树项的选中状态
                    treeItems.forEach(i => i.classList.remove('selected'));
                    // 添加目标树项的选中状态
                    targetTreeItem.classList.add('selected');
                }
                
                // 获取右侧内容区域元素
                const rightContent1 = document.querySelector('.right-content-1');
                const rightContent2 = document.querySelector('.right-content-2');
                
                // 根据treeType控制右侧内容区域的显示/隐藏
                if (targetTreeType === 'exhibition') {  // 网上展厅
                    rightContent1.style.display = 'grid';
                    rightContent2.style.display = 'none';
                } else if (targetTreeType === 'inquiry') {  // 朝阳兰台
                    rightContent1.style.display = 'none';
                    rightContent2.style.display = 'block';
                    // 切换到朝阳兰台数据
                    currentDataType = 'inquiry';
                    currentData = inquiryData;
                    currentPage = 1;
                    totalPages = Math.ceil(currentData.length / pageSize);
                    changePage(1);
                } else {
                    // 默认显示right-content-1
                    rightContent1.style.display = 'grid';
                    rightContent2.style.display = 'none';
                }
            }
        });
    });

    // 树形菜单点击事件
    treeTexts.forEach(item => {
        item.addEventListener('click', function () {
            // 移除所有树项的选中状态
            treeItems.forEach(i => i.classList.remove('selected'));
            // 添加当前点击项的选中状态
            this.parentElement.classList.add('selected');

            // 更新当前菜单显示
            const treeText = this.textContent;
            if (treeText) {
                currentMenuTitle.textContent = treeText;
            }

            // 获取当前点击项的数据属性
            const treeItem = this.parentElement;
            const treeType = treeItem.dataset.tree;

            // 获取右侧内容区域元素
            const rightContent1 = document.querySelector('.right-content-1');
            const rightContent2 = document.querySelector('.right-content-2');
            // 根据treeType控制右侧内容区域的显示/隐藏
            if (treeType === 'exhibition') {  // 网上展厅
                rightContent1.style.display = 'grid';
                rightContent2.style.display = 'none';
            } else if (treeType === 'inquiry') {  // 朝阳兰台
                rightContent1.style.display = 'none';
                rightContent2.style.display = 'block';
                // 切换到朝阳兰台数据
                currentDataType = 'inquiry';
                currentData = inquiryData;
                currentPage = 1;
                totalPages = Math.ceil(currentData.length / pageSize);
                changePage(1);
            } else if (treeType === 'culture') {  // 志鉴文化
                rightContent1.style.display = 'none';
                rightContent2.style.display = 'block';
                // 切换到志鉴文化数据
                currentDataType = 'culture';
                currentData = cultureData;
                currentPage = 1;
                totalPages = Math.ceil(currentData.length / pageSize);
                changePage(1);
            } else {
                // 默认显示right-content-1
                rightContent1.style.display = 'grid';
                rightContent2.style.display = 'none';
            }
        });
    });

    // 分页控件事件处理
    const prevBtn = document.querySelector('#prev-page');
    const nextBtn = document.querySelector('#next-page');
    const pageSizeSelect = document.querySelector('#page-size');
    const pageInput = document.querySelector('#page-input');

    if (prevBtn) {
        prevBtn.addEventListener('click', function () {
            changePage(currentPage - 1);
        });
    }

    if (nextBtn) {
        nextBtn.addEventListener('click', function () {
            changePage(currentPage + 1);
        });
    }

    if (pageSizeSelect) {
        pageSizeSelect.addEventListener('change', function () {
            changePageSize(this.value);
        });
    }

    if (pageInput) {
        // 为页码输入框添加回车和失焦事件
        pageInput.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                const page = parseInt(this.value);
                if (!isNaN(page)) {
                    changePage(page);
                } else {
                    this.value = currentPage;
                }
            }
        });

        // 添加鼠标离开时触发页面翻页
        pageInput.addEventListener('blur', function () {
            const page = parseInt(this.value);
            if (!isNaN(page)) {
                changePage(page);
            } else {
                this.value = currentPage;
            }
        });
    }
}

// 点击页面其他地方隐藏 submenu
function hideSubmenuOnClickOutside(e) {
    if (activeSubmenu && !activeSubmenu.contains(e.target) && !e.target.closest('.has-submenu')) {
        activeSubmenu.style.display = 'none';
        activeSubmenu = null;
    }
}

document.addEventListener('click', hideSubmenuOnClickOutside);

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    // 初始化数据
    inquiryData = generateInquiryData();
    cultureData = generateCultureData();
    
    // 解析URL参数，根据type参数设置对应的树形菜单选中状态
    const urlParams = new URLSearchParams(window.location.search);
    const contentType = urlParams.get('type');

    if (contentType) {
        // 查找对应的树形菜单项
        const targetTreeItem = document.querySelector(`.tree-item[data-tree="${contentType}"]`);
        if (targetTreeItem) {
            // 移除所有树项的选中状态
            treeItems.forEach(item => item.classList.remove('selected'));
            // 添加目标树项的选中状态
            targetTreeItem.classList.add('selected');

            // 更新当前菜单标题
            const menuTitle = targetTreeItem.textContent.trim();
            if (menuTitle && currentMenuTitle) {
                currentMenuTitle.textContent = menuTitle;
            }
            // 获取当前点击项的数据属性
            const treeType = targetTreeItem.dataset.tree;
            
            // 获取右侧内容区域元素
            const rightContent1 = document.querySelector('.right-content-1');
            const rightContent2 = document.querySelector('.right-content-2');
            // 根据treeType控制右侧内容区域的显示/隐藏
            if (treeType === 'exhibition') {  // 网上展厅
                rightContent1.style.display = 'grid';
                rightContent2.style.display = 'none';
            } else if (treeType === 'inquiry') {  // 朝阳兰台
                rightContent1.style.display = 'none';
                rightContent2.style.display = 'block';
                // 切换到朝阳兰台数据
                currentDataType = 'inquiry';
                currentData = inquiryData;
                currentPage = 1;
                totalPages = Math.ceil(currentData.length / pageSize);
                changePage(1);
            } else if (treeType === 'culture') {  // 志鉴文化
                rightContent1.style.display = 'none';
                rightContent2.style.display = 'block';
                // 切换到志鉴文化数据
                currentDataType = 'culture';
                currentData = cultureData;
                currentPage = 1;
                totalPages = Math.ceil(currentData.length / pageSize);
                changePage(1);
            } else {
                // 默认显示right-content-1
                rightContent1.style.display = 'grid';
                rightContent2.style.display = 'none';
            }
        }
    }

    // 初始化显示
    init();

    // 初始化 Tab 切换功能
    initTabs();
});

// 初始化 Tab 切换功能
function initTabs() {
    // 获取所有的 Tab 导航项和 Tab 内容面板
    const tabItems = document.querySelectorAll('.tab-item');
    const tabPanes = document.querySelectorAll('.tab-pane');

    // 为每个 Tab 导航项添加点击事件监听
    tabItems.forEach((tab, index) => {
        tab.addEventListener('click', () => {
            // 移除所有 Tab 导航项和 Tab 内容面板的 active 类
            tabItems.forEach(item => item.classList.remove('active'));
            tabPanes.forEach(pane => pane.classList.remove('active'));

            // 为当前点击的 Tab 导航项和对应的 Tab 内容面板添加 active 类
            tab.classList.add('active');
            tabPanes[index].classList.add('active');
        });
    });
}